// pages/profile/profile.js
const httpUtil = require("../../utils/httpUtil.js");
const globalCache = require("../../utils/cache.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '登录'
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  getUserInfo: function (e) {
    var errMsg = e.detail.errMsg;
    if (errMsg == "getUserInfo:ok") {
      var userInfo = e.detail.userInfo;
      var userId = this.saveUserInfoToCache(userInfo);

      var modifyData = new Object();
      modifyData.id = userId;
      modifyData.name = userInfo.nickName;
      modifyData.gender = userInfo.gender;
      modifyData.avatarUrl = userInfo.avatarUrl;
      modifyData.province = userInfo.province;
      modifyData.city = userInfo.city;
      modifyData.encryptedData = e.detail.encryptedData;
      modifyData.iv = e.detail.iv;

      var that = this;
      httpUtil.requestPost("modifyUserInfo", modifyData, function (res, that) {
        console.log("successfully update user info");
        wx.navigateBack({
          delta: 2
        })
      }, that, "提交中...");
    }
  },

  saveUserInfoToCache: function (userInfo) {
    var cacheUserInfo = globalCache.getUserInfo();
    cacheUserInfo.name = userInfo.nickName;
    cacheUserInfo.gender = userInfo.gender;
    cacheUserInfo.avatarUrl = userInfo.avatarUrl;
    cacheUserInfo.province = userInfo.province;
    cacheUserInfo.city = userInfo.city;
    globalCache.setUserInfo(cacheUserInfo);
    return cacheUserInfo.id;
  }
})